

import model.*;
import util.DateUtil;
import util.FileHandler;
import java.util.*;          // 覆盖Date、UUID、List等
import java.text.ParseException;
import service.UserService;
import service.MovieService;
import service.ShowService;
import service.TicketService;
import service.SalesData;

public class Main {
    private static Scanner scanner = new Scanner(System.in);
    private static UserService userService = new UserService();
    private static TicketService ticketService = new TicketService();
    private static ShowService showService = new ShowService(ticketService);
    private static MovieService movieService = new MovieService();
    private static List<CinemaHall> halls;
    private static List<Log> logs = new ArrayList<>();

    public static void main(String[] args) {
        initHalls();
        System.out.println("=====万东电影院管理系统=====");
        mainMenuLoop();
        FileHandler.writeLog(logs); // 退出时保存日志
    }

    // 初始化放映厅
    private static void initHalls() {
        halls = new ArrayList<>();
        halls.add(new CinemaHall("黄金厅", 8, 10));
        halls.add(new CinemaHall("白银厅", 10, 12));
        halls.add(new CinemaHall("翡翠厅", 7, 8));
        halls.add(new CinemaHall("钻石厅", 7, 8));
        halls.add(new CinemaHall("宝石厅", 8, 9));
    }

    // 主菜单循环
    private static void mainMenuLoop() {
        while (true) {
            System.out.println("\n【主菜单】");
            System.out.println("1. 用户登录");
            System.out.println("2. 退出系统");
            System.out.print("请选择: ");
            String choice = scanner.nextLine().trim();
            switch (choice) {
                case "1":
                    handleLogin();
                    break;
                case "2":
                    System.out.println("系统已退出，感谢使用！");
                    return;
                default:
                    System.out.println("输入错误，请重新选择（1-2）！");
            }
        }
    }

    // 处理登录
    private static void handleLogin() {
        System.out.println("\n=====用户登录=====");
        System.out.print("用户名: ");
        String username = scanner.nextLine().trim();
        System.out.print("密码: ");
        String password = scanner.nextLine().trim();

        User user = userService.findUser(username);
        if (user == null || !user.login(password)) {
            System.out.println("登录失败：用户名或密码错误！");
            return;
        }
        // 密码重置后强制修改
        if ("123456".equals(user.getPassword())) {
            System.out.println("检测到密码已重置，请立即修改！");
            if (!forceChangePassword(user)) {
                System.out.println("密码修改失败，强制退出！");
                return;
            }
        }

        System.out.println("登录成功！欢迎回来，" + user.getUsername());
        // 进入对应角色菜单
        if (user instanceof Admin) {
            adminMenu((Admin) user);
        } else if (user instanceof Manager) {
            managerMenu((Manager) user);
        } else if (user instanceof Receptionist) {
            receptionistMenu((Receptionist) user);
        }
    }

    // 强制修改密码
    private static boolean forceChangePassword(User user) {
        System.out.print("新密码: ");
        String newPwd = scanner.nextLine().trim();
        System.out.print("确认新密码: ");
        String confirmPwd = scanner.nextLine().trim();
        if (!newPwd.equals(confirmPwd) || newPwd.length() < 6) {
            System.out.println("密码不符合要求（长度≥6且两次输入一致）！");
            return false;
        }
        boolean success = user.changePassword("123456", newPwd);
        if (success) {
            userService.saveUsers();
            logs.add(new Log(new Date(), "首次登录修改密码", user.getUsername()));
        }
        return success;
    }

    // 管理员菜单
    private static void adminMenu(Admin admin) {
        while (true) {
            admin.showMenu();
            String choice = scanner.nextLine().trim();
            switch (choice) {
                case "1":
                    adminChangePassword(admin);
                    break;
                case "2":
                    adminResetPassword(admin);
                    break;
                case "3":
                    adminListUsers();
                    break;
                case "4":
                    adminDeleteUser(admin);
                    break;
                case "5":
                    adminQueryUser();
                    break;
                case "6":
                    adminAddUser(admin);
                    break;
                case "7":
                    adminUpdateUser();
                    break;
                case "8":
                    System.out.println("退出管理员登录！");
                    return;
                default:
                    System.out.println("输入错误，请选择1-8！");
            }
        }
    }

    // 管理员修改自身密码
    private static void adminChangePassword(Admin admin) {
        System.out.print("旧密码: ");
        String oldPwd = scanner.nextLine().trim();
        System.out.print("新密码: ");
        String newPwd = scanner.nextLine().trim();
        if (admin.changePassword(oldPwd, newPwd)) {
            userService.saveUsers();
            logs.add(new Log(new Date(), "修改管理员密码", admin.getUsername()));
            System.out.println("密码修改成功！");
        } else {
            System.out.println("旧密码错误，修改失败！");
        }
    }

    // 管理员重置用户密码
    private static void adminResetPassword(Admin admin) {
        System.out.println("1. 重置经理密码");
        System.out.println("2. 重置前台密码");
        System.out.print("选择用户类型: ");
        String type = scanner.nextLine().trim();
        String role = "经理";
        if ("2".equals(type)) role = "前台";
        else if (!"1".equals(type)) {
            System.out.println("输入错误！");
            return;
        }

        System.out.print("输入" + role + "用户名: ");
        String username = scanner.nextLine().trim();
        if (userService.resetPassword(username, role)) {
            logs.add(new Log(new Date(), "重置" + role + "密码:" + username, admin.getUsername()));
            System.out.println(role + "密码已重置为123456！");
        } else {
            System.out.println("重置失败，用户不存在！");
        }
    }

    // 管理员列出所有用户
    private static void adminListUsers() {
        List<User> users = userService.listAllUsers();
        if (users.isEmpty()) {
            System.out.println("无用户数据！");
            return;
        }
        System.out.println("\n=====用户列表=====");
        System.out.printf("%-10s %-10s %-20s %-10s %-15s%n",
                "用户ID", "用户名", "注册时间", "类型", "手机号");
        for (User user : users) {
            System.out.printf("%-10s %-10s %-20s %-10s %-15s%n",
                    user.getUserId(), user.getUsername(),
                    DateUtil.format(user.getRegisterTime()),
                    user.getUserType(), user.getPhone());
        }
    }

    // 管理员删除用户
    private static void adminDeleteUser(Admin admin) {
        System.out.print("输入要删除的用户名: ");
        String username = scanner.nextLine().trim();
        System.out.print("确认删除？(y/n): ");
        if (!"y".equals(scanner.nextLine().trim())) {
            System.out.println("已取消删除！");
            return;
        }
        if (userService.deleteUser(username)) {
            logs.add(new Log(new Date(), "删除用户:" + username, admin.getUsername()));
            System.out.println("删除成功！");
        } else {
            System.out.println("删除失败（用户不存在或为admin）！");
        }
    }

    // 管理员查询用户
    private static void adminQueryUser() {
        System.out.print("输入用户ID或用户名: ");
        String keyword = scanner.nextLine().trim();
        User user = userService.queryUser(keyword);
        if (user != null) {
            System.out.println("\n=====查询结果=====");
            System.out.println("用户ID: " + user.getUserId());
            System.out.println("用户名: " + user.getUsername());
            System.out.println("类型: " + user.getUserType());
            System.out.println("手机号: " + user.getPhone());
            System.out.println("注册时间: " + DateUtil.format(user.getRegisterTime()));
        } else {
            System.out.println("未找到该用户！");
        }
    }

    // 管理员添加用户
    private static void adminAddUser(Admin admin) {
        System.out.println("1. 添加管理员 2. 添加经理 3. 添加前台");
        System.out.print("选择用户类型: ");
        String type = scanner.nextLine().trim();
        if (!"1".equals(type) && !"2".equals(type) && !"3".equals(type)) {
            System.out.println("输入错误！");
            return;
        }

        System.out.print("用户ID: ");
        String userId = scanner.nextLine().trim();
        System.out.print("用户名: ");
        String username = scanner.nextLine().trim();
        System.out.print("手机号: ");
        String phone = scanner.nextLine().trim();
        Date now = new Date();

        User newUser = switch (type) {
            case "1" -> new Admin(userId, username, "123456", phone, now);
            case "2" -> new Manager(userId, username, "123456", phone, now);
            case "3" -> new Receptionist(userId, username, "123456", phone, now);
            default -> null;
        };

        if (newUser != null && userService.addUser(newUser)) {
            logs.add(new Log(now, "添加" + newUser.getUserType() + ":" + username, admin.getUsername()));
            System.out.println("用户添加成功，默认密码123456！");
        } else {
            System.out.println("添加失败（ID/用户名/手机号重复）！");
        }
    }

    // 管理员修改用户信息
    private static void adminUpdateUser() {
        System.out.print("输入用户名: ");
        String username = scanner.nextLine().trim();
        System.out.print("新用户类型(经理/前台): ");
        String newRole = scanner.nextLine().trim();
        System.out.print("新手机号: ");
        String newPhone = scanner.nextLine().trim();

        if (userService.updateUser(username, newPhone, newRole)) {
            System.out.println("修改成功！");
        } else {
            System.out.println("修改失败（用户不存在或手机号重复）！");
        }
    }

    // 经理菜单
    private static void managerMenu(Manager manager) {
        while (true) {
            manager.showMenu();
            String choice = scanner.nextLine().trim();
            switch (choice) {
                case "1":
                    managerChangePassword(manager);
                    break;
                case "2":
                    managerResetReceptionist(manager);
                    break;
                case "3":
                    movieManagement(manager);
                    break;
                case "4":
                    showManagement(manager);
                    break;
                case "5":
                    viewSalesData();
                    break;
                case "6":
                    System.out.println("退出经理登录！");
                    return;
                default:
                    System.out.println("输入错误，请选择1-6！");
            }
        }
    }

    // 经理修改自身密码
    private static void managerChangePassword(Manager manager) {
        System.out.print("旧密码: ");
        String oldPwd = scanner.nextLine().trim();
        System.out.print("新密码: ");
        String newPwd = scanner.nextLine().trim();
        if (manager.changePassword(oldPwd, newPwd)) {
            userService.saveUsers();
            System.out.println("密码修改成功！");
        } else {
            System.out.println("旧密码错误！");
        }
    }

    // 经理重置前台密码
    private static void managerResetReceptionist(Manager manager) { // 关键：接收manager参数
        System.out.print("前台用户名: ");
        String username = scanner.nextLine().trim();

        if (userService.resetPassword(username, "前台")) {
            // 现在manager是方法参数，可正常调用getUsername()
            logs.add(new Log(new Date(), "重置前台密码:" + username, manager.getUsername()));
            System.out.println("前台密码已重置为123456！");
        } else {
            System.out.println("重置失败！");
        }
    }

    // 影片管理子菜单
    private static void movieManagement(Manager manager) {
        while (true) {
            System.out.println("\n=====影片管理=====");
            System.out.println("1. 列出影片 2. 添加影片 3. 修改影片 4. 删除影片 5. 查询影片 6. 返回");
            System.out.print("选择功能: ");
            String choice = scanner.nextLine().trim();
            switch (choice) {
                case "1":
                    listMovies();
                    break;
                case "2":
                    addMovie(manager);
                    break;
                case "3":
                    updateMovie(manager);
                    break;
                case "4":
                    deleteMovie(manager);
                    break;
                case "5":
                    searchMovies();
                    break;
                case "6":
                    return;
                default:
                    System.out.println("输入错误！");
            }
        }
    }

    // 列出影片
    private static void listMovies() {
        List<Movie> movies = movieService.listAllMovies();
        if (movies.isEmpty()) {
            System.out.println("无影片数据！");
            return;
        }
        System.out.println("\n=====影片列表=====");
        System.out.printf("%-10s %-20s %-15s %-15s %-10s %-6s%n",
                "ID", "片名", "导演", "主演", "时长(分)", "评分");
        for (Movie m : movies) {
            System.out.printf("%-10s %-20s %-15s %-15s %-10d %-6.1f%n",
                    m.getId(), m.getName(), m.getDirector(), m.getActor(),
                    m.getDuration(), m.getScore());
        }
    }

    // 添加影片
    private static void addMovie(Manager manager) {
        String id = "MV" + UUID.randomUUID().toString().substring(0, 6);
        System.out.print("片名: ");
        String name = scanner.nextLine().trim();
        System.out.print("导演: ");
        String director = scanner.nextLine().trim();
        System.out.print("主演: ");
        String actor = scanner.nextLine().trim();
        System.out.print("剧情简介: ");
        String intro = scanner.nextLine().trim();
        System.out.print("时长(分钟): ");
        int duration = parseIntInput();
        System.out.print("评分(0-10): ");
        double score = parseDoubleInput(0, 10);

        Movie movie = new Movie(id, name, director, actor, intro, duration, score);
        if (movieService.addMovie(movie)) {
            System.out.println("影片添加成功，ID: " + id);
        } else {
            System.out.println("添加失败！");
        }
    }

    // 修改影片
    private static void updateMovie(Manager manager) {
        System.out.print("影片ID: ");
        String id = scanner.nextLine().trim();
        Movie movie = movieService.getMovieById(id);
        if (movie == null) {
            System.out.println("影片不存在！");
            return;
        }

        System.out.print("新片名(" + movie.getName() + "): ");
        String name = scanner.nextLine().trim();
        if (!name.isEmpty()) movie.setName(name);

        System.out.print("新导演(" + movie.getDirector() + "): ");
        String director = scanner.nextLine().trim();
        if (!director.isEmpty()) movie.setDirector(director);

        // 其他字段修改（主演、简介、时长、评分）
        System.out.print("新主演(" + movie.getActor() + "): ");
        String actor = scanner.nextLine().trim();
        if (!actor.isEmpty()) movie.setActor(actor);

        System.out.print("新简介(" + movie.getIntro() + "): ");
        String intro = scanner.nextLine().trim();
        if (!intro.isEmpty()) movie.setIntro(intro);

        System.out.print("新时长(" + movie.getDuration() + "): ");
        String durationStr = scanner.nextLine().trim();
        if (!durationStr.isEmpty()) {
            movie.setDuration(Integer.parseInt(durationStr));
        }

        System.out.print("新评分(" + movie.getScore() + "): ");
        String scoreStr = scanner.nextLine().trim();
        if (!scoreStr.isEmpty()) {
            movie.setScore(Double.parseDouble(scoreStr));
        }

        if (movieService.updateMovie(movie)) {
            System.out.println("影片修改成功！");
        } else {
            System.out.println("修改失败！");
        }
    }

    // 删除影片
    private static void deleteMovie(Manager manager) {
        System.out.print("影片ID: ");
        String id = scanner.nextLine().trim();
        Movie movie = movieService.getMovieById(id);
        if (movie == null) {
            System.out.println("影片不存在！");
            return;
        }

        System.out.print("确认删除《" + movie.getName() + "》？(y/n): ");
        if (!"y".equals(scanner.nextLine().trim())) {
            System.out.println("已取消！");
                        return;
        }

        if (movieService.deleteMovie(id, showService)) {
            System.out.println("删除成功！");
        } else {
            System.out.println("删除失败（影片有排片）！");
        }
    }

    // 搜索影片
    private static void searchMovies() {
        System.out.print("片名关键词: ");
        String name = scanner.nextLine().trim();
        System.out.print("导演关键词: ");
        String director = scanner.nextLine().trim();
        System.out.print("主演关键词: ");
        String actor = scanner.nextLine().trim();

        List<Movie> result = movieService.searchMovies(
                name.isEmpty() ? null : name,
                director.isEmpty() ? null : director,
                actor.isEmpty() ? null : actor
        );

        if (result.isEmpty()) {
            System.out.println("无匹配影片！");
            return;
        }

        System.out.println("\n=====搜索结果=====");
        for (Movie m : result) {
            System.out.println(m.getId() + " | " + m.getName() + " | " + m.getDirector() + " | " + m.getActor());
        }
    }

    // 排片管理子菜单
    private static void showManagement(Manager manager) {
        while (true) {
            System.out.println("\n=====排片管理=====");
            System.out.println("1. 增加场次 2. 修改场次 3. 删除场次 4. 列出场次 5. 自动排片 6. 返回");
            System.out.print("选择功能: ");
            String choice = scanner.nextLine().trim();
            switch (choice) {
                case "1":
                    addShow(manager);
                    break;
                case "2":
                    updateShow(manager);
                    break;
                case "3":
                    deleteShow(manager);
                    break;
                case "4":
                    listShows();
                    break;
                case "5":
                    autoArrangeShows(manager);
                    break;
                case "6":
                    return;
                default:
                    System.out.println("输入错误！");
            }
        }
    }

    // 增加场次
    private static void addShow(Manager manager) {
        String id = "SH" + UUID.randomUUID().toString().substring(0, 8);
        System.out.print("影片ID: ");
        String movieId = scanner.nextLine().trim();
        if (movieService.getMovieById(movieId) == null) {
            System.out.println("影片不存在！");
            return;
        }

        System.out.print("放映厅(黄金厅/白银厅/翡翠厅/钻石厅/宝石厅): ");
        String hallName = scanner.nextLine().trim();
        CinemaHall hall = getHallByName(hallName);
        if (hall == null) {
            System.out.println("放映厅不存在！");
            return;
        }

        System.out.print("放映时间(yyyy-MM-dd HH:mm): ");
        Date time = null;
        try {
            time = DateUtil.parse(scanner.nextLine().trim());
        } catch (ParseException e) {
            System.out.println("时间格式错误！");
            return;
        }

        System.out.print("票价: ");
        double price = parseDoubleInput(0, Double.MAX_VALUE);

        Show show = new Show(id, movieId, hallName, time, price, hall);
        if (showService.addShow(show)) {
            System.out.println("场次添加成功，ID: " + id);
        } else {
            System.out.println("添加失败（超出一周范围）！");
        }
    }

    // 修改场次
    private static void updateShow(Manager manager) {
        System.out.print("场次ID: ");
        String id = scanner.nextLine().trim();
        Show show = showService.getShowById(id);
        if (show == null) {
            System.out.println("场次不存在！");
            return;
        }

        System.out.print("新影片ID(" + show.getMovieId() + "): ");
        String movieId = scanner.nextLine().trim();
        if (!movieId.isEmpty() && movieService.getMovieById(movieId) == null) {
            System.out.println("新影片不存在！");
            return;
        }

        System.out.print("新时间(" + DateUtil.format(show.getTime()) + "): ");
        String timeStr = scanner.nextLine().trim();
        Date newTime = null;
        if (!timeStr.isEmpty()) {
            try {
                newTime = DateUtil.parse(timeStr);
            } catch (ParseException e) {
                System.out.println("时间格式错误！");
                return;
            }
        }

        System.out.print("新票价(" + show.getPrice() + "): ");
        String priceStr = scanner.nextLine().trim();
        Double newPrice = null;
        if (!priceStr.isEmpty()) {
            newPrice = Double.parseDouble(priceStr);
        }

        // 保存原影片名用于日志
        Movie oldMovie = movieService.getMovieById(show.getMovieId());
        String oldName = oldMovie != null ? oldMovie.getName() : "未知";

        // 执行修改
        if (!movieId.isEmpty()) show.setMovieId(movieId);
        if (newTime != null) show.setTime(newTime);
        if (newPrice != null) show.setPrice(newPrice);

        if (showService.updateShow(show)) {
            Movie newMovie = movieService.getMovieById(show.getMovieId());
            String newName = newMovie != null ? newMovie.getName() : "未知";
            logs.add(new Log(new Date(), "修改场次: " + DateUtil.format(show.getTime())
                    + ", 原片名:" + oldName + ", 新片名:" + newName, manager.getUsername()));
            System.out.println("修改成功！");
        } else {
            System.out.println("修改失败（场次有售票）！");
        }
    }

    // 删除场次
    private static void deleteShow(Manager manager) {
        System.out.print("场次ID: ");
        String id = scanner.nextLine().trim();
        Show show = showService.getShowById(id);
        if (show == null) {
            System.out.println("场次不存在！");
            return;
        }

        System.out.print("确认删除？(y/n): ");
        if (!"y".equals(scanner.nextLine().trim())) {
            System.out.println("已取消！");
            return;
        }

        if (showService.deleteShow(id)) {
            Movie movie = movieService.getMovieById(show.getMovieId());
            String name = movie != null ? movie.getName() : "未知";
            logs.add(new Log(new Date(), "删除场次: " + DateUtil.format(show.getTime())
                    + ", 片名:" + name, manager.getUsername()));
            System.out.println("删除成功！");
        } else {
            System.out.println("删除失败（场次有售票）！");
        }
    }

    // 列出场次
    private static void listShows() {
        System.out.println("1. 当日 2. 近3日 3. 近7日");
        System.out.print("选择时间范围: ");
        String choice = scanner.nextLine().trim();
        int days = 7;
        if ("1".equals(choice)) days = 1;
        else if ("2".equals(choice)) days = 3;

        List<Show> shows = showService.getShowsByDays(days);
        if (shows.isEmpty()) {
            System.out.println("无场次数据！");
            return;
        }

        System.out.println("\n=====场次列表=====");
        System.out.printf("%-25s %-20s %-10s %-20s %-10s%n",
                "ID", "影片名", "放映厅", "时间", "票价");
        for (Show s : shows) {
            Movie movie = movieService.getMovieById(s.getMovieId());
            String name = movie != null ? movie.getName() : "未知";
            System.out.printf("%-25s %-20s %-10s %-20s %-10.2f%n",
                    s.getId(), name, s.getHallName(),
                    DateUtil.format(s.getTime()), s.getPrice());
        }
    }

    // 自动排片
    private static void autoArrangeShows(Manager manager) {
        List<Movie> movies = movieService.listAllMovies();
        if (movies.isEmpty()) {
            System.out.println("无影片可排！");
            return;
        }
        showService.autoArrangeShows(movies, halls);
        logs.add(new Log(new Date(), "执行自动排片", manager.getUsername()));
        System.out.println("自动排片完成！");
    }

    // 查看销售数据
    private static void viewSalesData() {
        System.out.println("1. 当日 2. 当周 3. 当月");
        System.out.print("选择时间范围: ");
        String choice = scanner.nextLine().trim();
        String range = "当日";
        if ("2".equals(choice)) range = "当周";
        else if ("3".equals(choice)) range = "当月";

        SalesData data = ticketService.getSalesData(range);
        System.out.println("\n=====" + range + "销售数据=====");
        System.out.println("总售票数: " + data.getTotalTickets());
        System.out.println("总销售额: " + data.getTotalAmount() + "元");
        System.out.println("总退票数: " + data.getRefundTickets());
        System.out.println("总退票金额: " + data.getRefundAmount() + "元");
        System.out.println("实际收入: " + data.getNetIncome() + "元");
    }

    // 前台菜单
    private static void receptionistMenu(Receptionist receptionist) {
        while (true) {
            receptionist.showMenu();
            String choice = scanner.nextLine().trim();
            switch (choice) {
                case "1":
                    listMovies(); // 复用经理模块的方法
                    break;
                case "2":
                    listShows(); // 复用排片模块的方法
                    break;
                case "3":
                    viewSeats();
                    break;
                case "4":
                    sellTicket(receptionist);
                    break;
                case "5":
                    refundTicket(receptionist);
                    break;
                case "6":
                    System.out.println("退出前台登录！");
                    return;
                default:
                    System.out.println("输入错误，请选择1-6！");
            }
        }
    }

    // 查看座位
    private static void viewSeats() {
        System.out.print("场次ID: ");
        String showId = scanner.nextLine().trim();
        Show show = showService.getShowById(showId);
        if (show == null) {
            System.out.println("场次不存在！");
            return;
        }

        CinemaHall hall = show.getHall();
        Seat[][] seats = hall.getSeats();
        System.out.println("\n=====" + hall.getName() + "座位图=====");
        System.out.println("总座位: " + hall.getTotalSeats() + ", 空闲: " + hall.getAvailableSeats());
        System.out.println("(O:空闲 X:已售)");

        // 打印列号
        System.out.print("   ");
        for (int j = 0; j < seats[0].length; j++) {
            System.out.printf("%2d", j + 1);
        }
        System.out.println();

        // 打印座位
        for (int i = 0; i < seats.length; i++) {
            System.out.printf("%2d ", i + 1);
            for (int j = 0; j < seats[i].length; j++) {
                System.out.print(seats[i][j].isSold() ? "X " : "O ");
            }
            System.out.println();
        }
    }

    // 售票
    private static void sellTicket(Receptionist receptionist) {
        System.out.print("场次ID: ");
        String showId = scanner.nextLine().trim();
        Show show = showService.getShowById(showId);
        if (show == null) {
            System.out.println("场次不存在！");
            return;
        }
        Movie movie = movieService.getMovieById(show.getMovieId());
        if (movie == null) {
            System.out.println("影片不存在！");
            return;
        }

        System.out.print("购票数量: ");
        int count = parseIntInput(1, 10); // 单次最多10张
        List<int[]> seats = new ArrayList<>();
        for (int i = 0; i < count; i++) {
            System.out.print("第" + (i + 1) + "个座位(行 列): ");
            String[] pos = scanner.nextLine().trim().split(" ");
            if (pos.length != 2) {
                System.out.println("格式错误！");
                return;
            }
            int row = Integer.parseInt(pos[0]);
            int col = Integer.parseInt(pos[1]);
            seats.add(new int[]{row, col});
        }

        // 执行售票
        System.out.println("\n=====购票成功=====");
        for (int[] pos : seats) {
            Ticket ticket = ticketService.sellTicket(show, movie, pos[0], pos[1]);
            if (ticket == null) {
                System.out.println("座位" + pos[0] + "行" + pos[1] + "列售票失败（已售或无效）！");
                continue;
            }
            System.out.println("票号: " + ticket.getId());
            System.out.println("影片: " + ticket.getMovieName());
            System.out.println("时间: " + DateUtil.format(ticket.getShowTime()));
            System.out.println("座位: " + ticket.getRow() + "行" + ticket.getCol() + "列");
            System.out.println("票价: " + ticket.getPrice() + "元");
            System.out.println("-------------------");
        }
    }

    // 退票
    private static void refundTicket(Receptionist receptionist) {
        System.out.print("电子票号: ");
        String ticketId = scanner.nextLine().trim();
        if (ticketService.refundTicket(ticketId)) {
            logs.add(new Log(new Date(), "退票: " + ticketId, receptionist.getUsername()));
            System.out.println("退票成功！");
        } else {
            System.out.println("退票失败（票号无效或距开场不足1小时）！");
        }
    }

    // 工具方法：根据名称获取放映厅
    private static CinemaHall getHallByName(String name) {
        for (CinemaHall hall : halls) {
            if (hall.getName().equals(name)) {
                return hall;
            }
        }
        return null;
    }

    // 工具方法：安全解析整数
    private static int parseIntInput() {
        while (true) {
            try {
                return Integer.parseInt(scanner.nextLine().trim());
            } catch (NumberFormatException e) {
                System.out.print("请输入整数: ");
            }
        }
    }

    // 带范围的整数解析
    private static int parseIntInput(int min, int max) {
        while (true) {
            int num = parseIntInput();
            if (num >= min && num <= max) {
                return num;
            }
            System.out.printf("请输入%d-%d之间的整数: ", min, max);
        }
    }

    // 带范围的小数解析
    private static double parseDoubleInput(double min, double max) {
        while (true) {
            try {
                double num = Double.parseDouble(scanner.nextLine().trim());
                if (num >= min && num <= max) {
                    return num;
                }
                System.out.printf("请输入%.2f-%.2f之间的数字: ", min, max);
            } catch (NumberFormatException e) {
                System.out.print("请输入数字: ");
            }
        }
    }
}
